import { Call } from "./Call";
import { HttpAdapter } from "./HttpAdapter";
import { Request } from "./Reqest";
import { Response } from "./Response";
import { AsyncCallback } from "@kit.BasicServicesKit";

export class CallFactory {
  private httpAdapter: HttpAdapter;

  constructor(httpAdapter: HttpAdapter) {
    this.httpAdapter = httpAdapter;
  }

  /**
   * 创建Call
   * @param request
   * @returns
   */
  buildCall(request: Request): Call<any> {
    let call: Call<any> = {
      execute(): Promise<Response<any>> {
        return this.httpAdapter.call(request);
      },
      enqueue(callback: AsyncCallback<Response<any>>) {
        this.httpAdapter.call(request)
          .then((result) => {
            callback(undefined, result)
          })
          .catch((error) => {
            callback(error, undefined);
          });
      }
    };
    call['httpAdapter'] = this.httpAdapter
    return call;
  }
}